package tk.ovzs.PageScraper;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import tk.ovzs.DataModels.UserProfile;
import tk.ovzs.Tools.AsyncHttpClient;
import tk.ovzs.Tools.AsyncHttpResponseHandler;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class WebPageScraper
{
	private String URL;
	private Document docum;
	private static UserProfile userProfile;
	
	public WebPageScraper(String uRL)
	{
		super();
		URL = uRL;
	}
	
	
	
	public static void parseDocument (Document docum)
	{		
		userProfile = UserProfile.getInstance();

		Elements userName = docum.getElementsByClass("last");

		for (Element current : userName)
		{
			if (current.hasClass("last"))
			{
				userProfile.setUserName(current.getElementsByTag("a").text());
				break;
			}
		}

		Element userProfileTag = docum.getElementById("profile-right");

		Elements userLeague = userProfileTag.getElementsByAttributeValueContaining("class", "badge-medium-1");

		if (userLeague.size() > 0)
		{
			String userLeg = ((Element) userLeague.get(0)).attr("class");
			StringTokenizer tokenizer = new StringTokenizer(userLeg, " ", false);

			while (tokenizer.hasMoreTokens())
			{
				userLeg = tokenizer.nextToken();
				if (userLeg.equals("badge-master"))
				{
					userProfile.setUserLeague("Master");
					break;
				}			
				else if (userLeg.equals("badge-diamond"))
				{
					userProfile.setUserLeague("Diamond");
					break;
				}
				else if (userLeg.equals("badge-gold"))
				{
					userProfile.setUserLeague("Gold");
					break;
				}
			}
		}

		Element test = userProfileTag.getElementById("best-team-1");

		//Element test = docum.getElementById("badge badge-master badge-medium-1");
		//			Elements userLeague = test.getElementsByTag("span");

		Elements teste = test.getElementsByTag("div");
		for (Element tag : teste)
		{
			if (!tag.text().startsWith("Highest") && !tag.text().startsWith("Not"))					
			{
				StringTokenizer tokenizer = new StringTokenizer(tag.text(), " :", false);

				if (tokenizer.countTokens() > 0)
				{
					while(tokenizer.hasMoreTokens())
					{		
						String token = tokenizer.nextToken();
						if (token.equals("Division"))
						{
							if (tokenizer.hasMoreElements())
							{
								token = tokenizer.nextToken();
							}
						}

						if (!token.equals("Rank"))
						{
							if (userProfile.getUserDivision1() == null)
							{
								userProfile.setUserDivision1(token);
							}
							else
							{
								userProfile.setUserDivision1(userProfile.getUserDivision1() + " " + token);
							}
						}
						else
						{
							if (tokenizer.hasMoreTokens())
							{
								userProfile.setUserRank1(Integer.valueOf(tokenizer.nextToken()));
							}
						}
					}
				}					
			}
		}			
		if (userProfile.getUserDivision1() == null)
		{
			userProfile.setUserDivision1("Not yet Ranked");
			userProfile.setUserRank1(0);
		}

		test = userProfileTag.getElementById("best-team-2");			

		teste = test.getElementsByTag("div");
		for (Element tag : teste)
		{
			if (!tag.text().startsWith("Highest") && !tag.text().startsWith("Not"))					
			{
				StringTokenizer tokenizer = new StringTokenizer(tag.text(), " :", false);

				if (tokenizer.countTokens() > 0)
				{
					while(tokenizer.hasMoreTokens())
					{		
						String token = tokenizer.nextToken();
						if (token.equals("Division"))
						{
							if (tokenizer.hasMoreElements())
							{
								token = tokenizer.nextToken();
							}
						}

						if (!token.equals("Rank"))
						{
							if (userProfile.getUserDivision2() == null)
							{
								userProfile.setUserDivision2(token);
							}
							else
							{
								userProfile.setUserDivision2(userProfile.getUserDivision2() + " " + token);
							}
						}
						else
						{
							if (tokenizer.hasMoreTokens())
							{
								userProfile.setUserRank2(Integer.valueOf(tokenizer.nextToken()));
							}
						}


					}
				}					
			}
		}			
		if (userProfile.getUserDivision2() == null)
		{
			userProfile.setUserDivision2("Not yet Ranked");
			userProfile.setUserRank2(0);
		}

		test = userProfileTag.getElementById("best-team-3");			

		teste = test.getElementsByTag("div");
		for (Element tag : teste)
		{
			if (!tag.text().startsWith("Highest") && !tag.text().startsWith("Not"))					
			{
				StringTokenizer tokenizer = new StringTokenizer(tag.text(), " :", false);

				if (tokenizer.countTokens() > 0)
				{
					while(tokenizer.hasMoreTokens())
					{		
						String token = tokenizer.nextToken();
						if (token.equals("Division"))
						{
							if (tokenizer.hasMoreElements())
							{
								token = tokenizer.nextToken();
							}
						}

						if (!token.equals("Rank"))
						{
							if (userProfile.getUserDivision3() == null)
							{
								userProfile.setUserDivision3(token);
							}
							else
							{
								userProfile.setUserDivision3(userProfile.getUserDivision3() + " " + token);
							}
						}
						else
						{
							if (tokenizer.hasMoreTokens())
							{
								userProfile.setUserRank3(Integer.valueOf(tokenizer.nextToken()));
							}
						}


					}
				}					
			}
		}			
		if (userProfile.getUserDivision3() == null)
		{
			userProfile.setUserDivision3("Not yet Ranked");
			userProfile.setUserRank3(0);
		}

		test = userProfileTag.getElementById("best-team-4");			

		teste = test.getElementsByTag("div");
		for (Element tag : teste)
		{
			if (!tag.text().startsWith("Highest") && !tag.text().startsWith("Not"))					
			{
				StringTokenizer tokenizer = new StringTokenizer(tag.text(), " :", false);

				if (tokenizer.countTokens() > 0)
				{
					while(tokenizer.hasMoreTokens())
					{		
						String token = tokenizer.nextToken();
						if (token.equals("Division"))
						{
							if (tokenizer.hasMoreElements())
							{
								token = tokenizer.nextToken();
							}
						}

						if (!token.equals("Rank"))
						{
							if (userProfile.getUserDivision4() == null)
							{
								userProfile.setUserDivision4(token);
							}
							else
							{
								userProfile.setUserDivision4(userProfile.getUserDivision4() + " " + token);
							}
						}
						else
						{
							if (tokenizer.hasMoreTokens())
							{
								userProfile.setUserRank4(Integer.valueOf(tokenizer.nextToken()));
							}
						}


					}
				}					
			}
		}			
		if (userProfile.getUserDivision4() == null)
		{
			userProfile.setUserDivision4("Not yet Ranked");
			userProfile.setUserRank4(0);
		}

		Elements wins = userProfileTag.getElementsByClass("division");
		for (Element tag : wins)
		{
			if (tag.text().contains("1v1"))
			{		
				Elements games = tag.nextElementSibling().getElementsByClass("totals");			
				for (Element total : games)
				{
					try 
					{
						if (!total.text().startsWith("No Games") && total.text().contains("Games"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Games"))
								{
									userProfile.setUserGamePlayed1(Integer.valueOf(token));
									break;
								}
							}
						}
						else if (total.text().contains("Wins"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Wins"))
								{
									userProfile.setUserGameWins1(Integer.valueOf(token));
									break;
								}
							}
						}
						else
						{
							userProfile.setUserGameWins1(0);
							userProfile.setUserGamePlayed1(0);
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
			else if (tag.text().contains("2v2"))
			{
				Elements games = tag.nextElementSibling().getElementsByClass("totals");			
				for (Element total : games)
				{
					try 
					{
						if (!total.text().startsWith("No Games") && total.text().contains("Games"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Games"))
								{
									userProfile.setUserGamePlayed2(Integer.valueOf(token));
									break;
								}
							}
						}
						else if (total.text().contains("Wins"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Wins"))
								{
									userProfile.setUserGameWins2(Integer.valueOf(token));
									break;
								}
							}
						}
						else
						{
							userProfile.setUserGameWins2(0);
							userProfile.setUserGamePlayed2(0);
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
			else if (tag.text().contains("3v3"))
			{
				Elements games = tag.nextElementSibling().getElementsByClass("totals");			
				for (Element total : games)
				{
					try 
					{
						if (!total.text().startsWith("No Games") && total.text().contains("Games"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Games"))
								{
									userProfile.setUserGamePlayed3(Integer.valueOf(token));
									break;
								}
							}
						}
						else if (total.text().contains("Wins"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Wins"))
								{
									userProfile.setUserGameWins3(Integer.valueOf(token));
									break;
								}
							}
						}
						else
						{
							userProfile.setUserGameWins3(0);
							userProfile.setUserGamePlayed3(0);
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
			else if (tag.text().contains("4v4"))
			{
				Elements games = tag.nextElementSibling().getElementsByClass("totals");			
				for (Element total : games)
				{
					try 
					{
						if (!total.text().startsWith("No Games") && total.text().contains("Games"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Games"))
								{
									userProfile.setUserGamePlayed4(Integer.valueOf(token));
									break;
								}
							}
						}
						else if (total.text().contains("Wins"))
						{
							StringTokenizer tokenizer = new StringTokenizer(total.text(), " ", false);
							while (tokenizer.hasMoreTokens())
							{
								String token = tokenizer.nextToken();
								if (!token.contains("Wins"))
								{
									userProfile.setUserGameWins4(Integer.valueOf(token));
									break;
								}
							}
						}
						else
						{
							userProfile.setUserGameWins4(0);
							userProfile.setUserGamePlayed4(0);
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}								
		}	

		Elements footer = userProfileTag.getElementsByClass("module-footer");

		for (Element tag : footer)
		{
			if (tag.text().contains("Most"))
			{
				if (tag.text().contains("Protoss"))
				{
					userProfile.setUserMostPlayerRace("Protoss");
					break;
				}
				else if (tag.text().contains("Terrain"))
				{
					userProfile.setUserMostPlayerRace("Terrain");
					break;
				}
				else if (tag.text().contains("Zerg"))
				{
					userProfile.setUserMostPlayerRace("Zerg");
					break;
				}
				else if (tag.text().contains("Random"))
				{
					userProfile.setUserMostPlayerRace("Random");
					break;
				}
			}
		}		
	}
	
	public void pageRequest()
	{
		new Thread() {			
			
			public void run() {
				try 
				{							
					URL url = new URL(URL);
					docum = (Document) Jsoup.parse(url, 9000);
					if (docum != null)
					{
						messageHandler.sendEmptyMessage(0);
					}
					else
					{
						messageHandler.sendEmptyMessage(1);
					}
				}
				catch (IOException e)
				{
					messageHandler.sendEmptyMessage(1);
				}
			}
		}.start();
	}
	
	private Handler messageHandler = new Handler() {

		public void handleMessage(Message msg) 
		{			
			Log.d("misc", "received message: " + msg);

//			if (msg.get == 0)
//			{
				WebPageScraper.parseDocument(docum);
				userProfile = UserProfile.getInstance();
//				showWidget();
//				}
//			}

			super.handleMessage(msg);	
		}
	};
	
	public String getXmlFromUrl(String url)
	{
        String xml = null;
 
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
 
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }
	
//	public Document getDomElement(String xml)
//	{
//        Document doc = null;
//        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//        try {
// 
//            DocumentBuilder db = dbf.newDocumentBuilder();
// 
//            InputSource is = new InputSource();
//                is.setCharacterStream(new StringReader(xml));
////                doc = db.parse(is); 
// 
////            } catch (ParserConfigurationException e) {
////                Log.e("Error: ", e.getMessage());
////                return null;
////            } catch (SAXException e) {
////                Log.e("Error: ", e.getMessage());
////                return null;
////            } catch (IOException e) {
////                Log.e("Error: ", e.getMessage());
////                return null;
////            }
//                // return DOM
//            return doc;
//    }
	
//	public String getValue(Element item, String str) {
//	    NodeList n = item.getElementsByTagName(str);
//	    return this.getElementValue(n.item(0));
//	}
	 
	public final String getElementValue( Node elem ) {
	         Node child;
	         if( elem != null){
	             if (elem.hasChildNodes()){
	                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                     if( child.getNodeType() == Node.TEXT_NODE  ){
	                         return child.getNodeValue();
	                     }
	                 }
	             }
	         }
	         return "";
	  }  
	
//	public int 
}
